package com.iye.puretennis.fragment;

import android.content.Context;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
import com.iye.puretennis.R;
import com.iye.puretennis.custom.HuaWenHuPoTextView;
import com.iye.puretennis.custom.IdolDropdownAdapter;
import com.iye.puretennis.custom.UserInfoFragment;
import com.iye.puretennis.custom.ViewCache;
import com.iye.puretennis.domain.Idol;
import com.iye.puretennis.domain.UrlSuffix;
import com.iye.puretennis.domain.UserToken;
import com.iye.puretennis.helper.*;
import com.iye.puretennis.utils.ImageUtils;
import com.iye.puretennis.utils.StringUtils;
import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: jing wu
 * Date: 2014/12/4
 * Time: 9:16
 */
public class FriendsRequestFragment extends TabFragment {

    public static final String TAG = "friends_request";

    private TextView requestAmountView;

    private ListView invitationsView;

    private List<FriendRequest> friendRequests = new ArrayList<FriendRequest>();

    private FriendsRequestsAdapter friendsRequestsAdapter;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        super.onCreateView(inflater, container, savedInstanceState);

        requestAmountView = (TextView) mainView.findViewById(R.id.request_amount);

        invitationsView = (ListView) mainView.findViewById(R.id.myinvitations_list);


        friendsRequestsAdapter = new FriendsRequestsAdapter(getActivity(), R.layout.myfriend_invitation_item);

        invitationsView.setAdapter(friendsRequestsAdapter);



        return mainView;
    }




    @Override
    public int getViewId() {
        return R.layout.friend_request;
    }

    @Override
    public int getSourceId() {
        return R.id.friend_request;
    }

    @Override
    public void updateUI() {

        invitationsListRender(token);

    }

    private void invitationsListRender(final UserToken token) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                json = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.FRIENDS_REQUESTS), token.getToken());
                getActivity().runOnUiThread(uiInvitationsUpdate);
            }
        }).start();
    }

    private Runnable uiInvitationsUpdate = new Runnable() {
        @Override
        public void run() {
            if (!Constant.RESPONSE_BADLY.equals(json)) {
                try {
                    friendRequests.clear();//remove old data
                    final JSONArray requestsArray = new JSONArray(json);
                    final int length = requestsArray.length();
                    for (int i = 0; i < length; i++) {
                        JSONObject requestObj = requestsArray.getJSONObject(i);
                        String guid = requestObj.getString("guid");
                        JSONObject senderObj = requestObj.getJSONObject("sender");
                        String senderGuid = senderObj.getString("guid");
                        String senderName = senderObj.getString("nickname");
                        String imageBase64Byte = senderObj.getString("imageBase64Byte");
                        friendRequests.add(new FriendRequest(guid, senderGuid, senderName, imageBase64Byte));
                    }
                    friendsRequestsAdapter.notifyDataSetChanged();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            requestAmountView.setText(length + "");
                            TextView textView = (TextView) mainView.findViewById(R.id.empty);
                            invitationsView.setEmptyView(textView);
                            invitationsView.setVisibility(View.VISIBLE);
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    };


    private class FriendsRequestsAdapter extends BaseAdapter {
        private int resource;//数据绑定在哪个资源界面上
        private LayoutInflater inflater;//布局填充器,可以使用xml文件来生成它的view对象
        private ViewCache viewCache;

        private FriendsRequestsAdapter(Context context, int resource) {
            this.resource = resource;
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return friendRequests.size();
        }

        @Override
        public Object getItem(int position) {
            return friendRequests.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public void removeItem(int position) {
            friendRequests.remove(position);
            this.notifyDataSetChanged();
            requestAmountView.setText(friendRequests.size() + "");
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            HuaWenHuPoTextView nameView;
            ImageView photoView;
            if (convertView == null) {//第一次渲染
                convertView = inflater.inflate(resource, null);
                nameView = (HuaWenHuPoTextView) convertView.findViewById(R.id.myfriend_invitation_name);
                photoView = (ImageView) convertView.findViewById(R.id.user_photo);
                viewCache = new ViewCache(nameView, photoView);

                convertView.setTag(viewCache);
            } else {
                viewCache = (ViewCache) convertView.getTag();
                nameView = viewCache.getNameView();
                photoView = viewCache.getImageView();
            }

            final FriendRequest friendRequest = friendRequests.get(position);

            nameView.setText(friendRequest.getSenderName());

            String avatar = friendRequest.getSenderImageBase64Byte();

            if (StringUtils.hasText(avatar)) {
                photoView.setImageBitmap(ImageUtils.base64ToBitmap(avatar));
            }

            convertView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {

                    showPopupMenu(view,R.menu.details_accept_reject_menu,new PopupMenu.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem menuItem) {
                            int menuItemItemId = menuItem.getItemId();
                            if (menuItemItemId == R.id.details_menu) {

                                Session session = Session.newSession();
                                session.put("userGuid", friendRequest.getGuid());
                                goFragment(R.id.search_friend, UserInfoFragment.TAG, UserInfoFragment.class, null, false);
                            } else if (menuItemItemId == R.id.accept_menu) {
                                acceptInvitation(friendRequest, position);
                            } else {
                                rejectInvitation(friendRequest, position);
                            }
                            return true;
                        }
                    });
                    return true;
                }
            });
            return convertView;
        }


        private void rejectInvitation(final FriendRequest friendRequest, final int position) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    JSONObject paramJson = new JSONObject();
                    try {
                        paramJson.put("guid", friendRequest.getGuid());
                        StringEntity paramEntity = new StringEntity(paramJson.toString(), Constant.CHARSET_UTF8);
                        String result = ServerAccessHelper.queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.FRIENDS_REQUEST_REJECT), token.getToken(), paramEntity);
                        if (!Constant.RESPONSE_BADLY.equals(result)) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    removeItem(position);
                                }
                            });
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

        private void acceptInvitation(final FriendRequest friendRequest, final int position) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    JSONObject paramJson = new JSONObject();
                    try {
                        paramJson.put("guid", friendRequest.getGuid());
                        StringEntity paramEntity = new StringEntity(paramJson.toString(), Constant.CHARSET_UTF8);
                        String result = ServerAccessHelper.queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.FRIENDS_REQUEST_ACCEPT), token.getToken(), paramEntity);
                        if (!Constant.RESPONSE_BADLY.equals(result)) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    removeItem(position);
                                }
                            });
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }


    }


    private class FriendRequest {

        private String guid;

        private String senderGuid;

        private String senderName;

        private String senderImageBase64Byte;

        private FriendRequest(String guid, String senderGuid, String senderName, String senderImageBase64Byte) {
            this.guid = guid;
            this.senderGuid = senderGuid;
            this.senderName = senderName;
            this.senderImageBase64Byte = senderImageBase64Byte;
        }

        public String getGuid() {
            return guid;
        }

        public String getSenderGuid() {
            return senderGuid;
        }

        public String getSenderName() {
            return senderName;
        }

        public String getSenderImageBase64Byte() {
            return senderImageBase64Byte;
        }
    }


}
